package com.neuedu.shop.controller;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author ${秦}
 * @Date 2021/4/15 16:24
 */
@Controller
public class CodeController {
    private static final int WIDTH = 120;// 生成的图片的宽度
    private static final int HEIGHT = 30;// 生成的图片的高度
    @RequestMapping("/code")
    public void generateCode(HttpServletResponse response, HttpSession session) throws IOException {
        System.out.println("进来了");
        //生成验证码图片
        //1.设置向前台输出的文件类型
        response.setContentType("image/jpeg");
        /* 2 画图 */
        //BufferedImage:内存映象对象
        BufferedImage image = new BufferedImage(60, 20,BufferedImage.TYPE_INT_RGB);
        Random r = new Random();
        //获得画笔
        Graphics g = image.getGraphics();
        //设置背景颜色
        g.setColor(new Color(255,255,255));
        //填充背景颜色
        g.fillRect(0, 0, 60, 20);
        //在图片上画干扰线
        drawRandomLine(g);
        //设置前景颜色
        g.setColor(new Color(33, 31, 31));
        //生成随机数
        String number = String.valueOf(r.nextInt(100_000));
        //将生成的number随机数绑定到session对象中
        session.setAttribute("number",number);
        //画到图片上
        g.drawString(number, 5, 15);
        /* 3 压缩图片并输出 */
        //获得字节输出流，因为要输出的是图像压缩之后
        //的字节数组，所以，不能用PrintWriter。
        OutputStream os = response.getOutputStream();
        //将图片压缩，输出
        JPEGImageEncoder encoder =  JPEGCodec.createJPEGEncoder(os);
        encoder.encode(image);
    }
    private void drawRandomLine(Graphics g) {
        // 设置颜色
        g.setColor(Color.GREEN);
        // 设置线条个数并画线
        for (int i = 0; i < 5; i++) {
            int x1 = new Random().nextInt(WIDTH);
            int y1 = new Random().nextInt(HEIGHT);
            int x2 = new Random().nextInt(WIDTH);
            int y2 = new Random().nextInt(HEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }
    }
}
